package com.bdq.common.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.bdq.common.constants.Constant;

import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * @author malei
 * @date 2024-05-07 14:13
 */
public class TokenUtil {

    /**
     * 生成Token
     *
     * @param userMobile
     * @return
     */
    public static String createToken(String userMobile) {
        AES aes = new AES(Constant.TOKEN_SECRET_KEY.getBytes());
        String dateTimeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern(Constant.DateTimePattern.pFirst));
        String content = dateTimeStr.concat(userMobile);
        return aes.encryptHex(content);
    }

    /**
     * 获取手机号
     *
     * @param token
     * @return
     */
    public static String getUserMobile(String token) {
        AES aes = new AES(Constant.TOKEN_SECRET_KEY.getBytes());
        String content = aes.decryptStr(token);
        return content.substring(content.length() - 11);
    }

    /**
     * token验证
     *
     * @param token
     * @return
     */
    public static boolean vefiry(String token) {
        String userMobile = getUserMobile(token);
        String cacheToken = RedisUtil.get(String.format(Constant.RedisKeyTemplate.USER_TOKEN, userMobile));
        return !StrUtil.isBlank(cacheToken) && cacheToken.equals(token);
    }
}
